﻿using B.S.GridManage.Api.Read.Application.Command.PhisicalGrid;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;

namespace B.S.GridManage.Api.Read.Application.Handler.PhisicalGrid
{
    public class SearchPhysicalHandler : IRequestHandler<SearchPhysicalCommand, ApiResult<List<PhysicalGridDto>>>
    {
        private readonly IBaseRepository<AreaModel> areaRepo;
        private readonly IBaseRepository<PhysicallGridModel> physicallGridRepo;

        public SearchPhysicalHandler(IBaseRepository<AreaModel> areaRepo, IBaseRepository<PhysicallGridModel> physicallGridRepo)
        {
            this.areaRepo = areaRepo;
            this.physicallGridRepo = physicallGridRepo;
        }
        public Task<ApiResult<List<PhysicalGridDto>>> Handle(SearchPhysicalCommand request, CancellationToken cancellationToken)
        {
            //响应包装类
            ApiResult<List<PhysicalGridDto>>  res = new ApiResult<List<PhysicalGridDto>>();

            //表达式
            var physicalGrids = physicallGridRepo.GetAll().Where(x=>!x.IsDeleted); 
            var areas = areaRepo.GetAll().Where(x=>!x.IsDeleted);

            //条件
            if (!string.IsNullOrEmpty(request.AreaName)) {
                areas = areas.Where(x=>x.AreaName.Contains(request.AreaName));
            }
            if (!string.IsNullOrEmpty(request.GridName))
            {
                physicalGrids = physicalGrids.Where(x => x.GridName.Contains(request.GridName));
            }

            //组合查询
            var linq = from grid in physicalGrids
                       join a in areas on grid.AreaId equals a.Id
                       select new PhysicalGridDto
                       {
                           Id = grid.Id,
                           AreaId = grid.AreaId,
                           GridCode = grid.GridCode,
                           GridName = grid.GridName,
                           AreaName = a.AreaName
                       };

            //数据 
            res.Data = linq.ToList();
            res.Code = ApiEnum.Success;
            res.Msg = "查询物理网格列表成功!";

            return Task.FromResult(res) ;


        }
    }
}
